package cn.watson.org.service.impl;

import cn.watson.basic.service.impl.BaseServiceImpl;
import cn.watson.basic.utils.MD5Utils;
import cn.watson.basic.utils.StrUtils;
import cn.watson.org.domain.Employee;
import cn.watson.org.mapper.EmployeeMapper;
import cn.watson.org.service.IEmployeeService;
import cn.watson.user.domain.Logininfo;
import cn.watson.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service

public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
    * @Title: save
    * @Description: 复写新增方法，实现logininfo表的信息是在操作user、employee表数据时同步修改的，
    *               不管是增、删、改都应该进行logininfo表的相应操作
    * @Author: ZhangRui
    * @Version: 1.0
    * @Date:  2022/7/6 22:59
    * @Parameters: [employee]
    * @Return void
    */
    public void save(Employee employee){
        // 初始化employee，然后保存
        initEmployee(employee);
        employeeMapper.save(employee);
        // 初始化logininfo,然后保存
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        // 3.将logininfo的主键Id设置到employee的外键，并修改
        employee.setLogininfoId(logininfo.getId());
    }


    /**
    * @Title: initEmployee
    * @Description: 复写employee
    * @Author: ZhangRui
    * @Version: 1.0
    * @Date:  2022/7/6 23:05
    * @Parameters: [employee]
    * @Return void
    */
    private void initEmployee(Employee employee){
        // 初始化employee表中的盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码使用MD5加密，然后加上盐值
        String saltPassword = MD5Utils.encrypByMd5(salt + employee.getPassword());

        employee.setSalt(salt);
        employee.setPassword(saltPassword);
    }

    /**
    * @Title: employee2Logininfo
    * @Description: 将employee的数据 拷贝到logininfo中
    * @Author: ZhangRui
    * @Version: 1.0
    * @Date:  2022/7/6 23:09
    * @Parameters: [employee]
    * @Return cn.watson.user.domain.Logininfo
    */
    private Logininfo employee2Logininfo(Employee employee){
        Logininfo logininfo = new Logininfo();
        // 拷贝数据
        BeanUtils.copyProperties(employee, logininfo);
        // 设置用户类型为员工
        logininfo.setType(0);
        return logininfo;
    }



    public void update(Employee employee){
        super.update(employee);
    }


    public void remove(Long id){
        super.remove(id);
    }


}
